import {
    readStorage
} from "../../../common/utils/storageUtil";
import {
    request2Promise,
    apiGET,
    apiPOST
} from "@/common/services/apiRequest.js"

/**
 * 微信登录
 */
function wxLogin() {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: "weixin",
            onlyAuthorize: true,
            success: (res) => {
                if (res) {
                    resolve(res.code);
                } else {
                    reject();
                }
            },
            fail: (error) => {
                reject();
            }

        })
    })
}

/**
 * 获取openID 和 sessionKey
 * @param {Object} code
 */
function getOpenId(code) {
    return request2Promise(apiPOST, {
        url: "/getJsCode2Session",
        data: {
            code
        }
    })
}

/**
 * 登录
 * @param {Object} code
 */
function loginAction(openId, encryptedData, iv, sessionKey, avatarUrl, nickName, gender) {
    return request2Promise(apiPOST, {
        url: "/appLogin",
        data: {
            openId,
            encryptedData,
            iv,
            sessionKey,
            avatarUrl,
            nickName,
            gender
        }
    })
}

// 退出登录
function logout() {
    return new Promise(resolve => {
        resolve()
    })
    const userInfo = readStorage()
    return request2Promise(apiGET, {
        url: `/logout`
    })
}

module.exports = {
    wxLogin,
    getOpenId,
    loginAction,
    logout
}